import React, { useEffect, useState } from 'react';
import { Tooltip } from 'antd';
import type { IOptionType } from '../../type';
import styles from './index.less';

type Tprops = {
  /**
   * 默认值
   */
  defaultValue?: unknown;
  /**
   * 值
   */
  value?: unknown;
  /**
   * 是否禁用
   */
  disabled?: boolean;
  /**
   * 选项
   */
  options?: IOptionType[];
  /**
   * 函数
   */
  onChange?: (e: any) => void;
};

const RadioGroup = (props: Tprops) => {
  const { onChange, value: _value, disabled = false, options = [], defaultValue } = props;
  const [value, setValue] = useState<unknown>(defaultValue);

  useEffect(() => {
    if (_value || _value === 0 || defaultValue || defaultValue === 0) {
      setValue(_value || defaultValue);
    }
  }, [_value]);

  const _onChange = (e: IOptionType) => {
    if (e?.value !== _value && !disabled && !e?.disabled) {
      setValue(e?.value as unknown);
      onChange && onChange(e?.value);
    }
  };
  return options?.length > 0 ? (
    <div className={styles.container}>
      <div className="tianji-radio-container">
        {options.map((item) => {
          return (
            <div
              className={`${'tianji-radio-item'} ${
                value === item?.value ? 'tianji-radio-checked-item' : ''
              } ${item?.disabled || disabled ? 'tianji-radio-disabled-item' : ''}`}
              key={item?.value}
              onClick={() => _onChange(item)}
            >
              <Tooltip placement="topLeft" title={item?.label || ''}>
                {item?.label || ''}
              </Tooltip>
            </div>
          );
        })}
      </div>
    </div>
  ) : null;
};

export default RadioGroup;
